/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzillahelp;

import com.yy.bugzillahelp.ui.option.OptionPanel;
import com.yy.bugzillahelp.action.server.ServerAction;
import com.yy.bugzillahelp.data.server.ServerData;
import com.yy.bugzillahelp.db.BugzillaHelpDB;
import com.yy.bugzillahelp.log.LoggerUtil;
import com.yy.bugzillahelp.timer.TimerCenter;
import com.yy.bugzillahelp.timer.TimerEvent;
import com.yy.bugzillahelp.tool.DateTool;
import com.yy.bugzillahelp.tool.SQLTool;
import com.yy.bugzillahelp.ui.server.ServerInfoPanel;
import com.yy.bugzillahelp.ui.server.ServerTree;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
//import javax.swing.plaf.synth.SynthTabbedPaneUI;

/**
 *
 * @author hualun-alan
 */
public class MainFrame extends javax.swing.JFrame {

    public static final ServerData CONNECT_DATA = new ServerData("2012-12-05 11:07:41", "内部Bugzilla", "http://66.239.64.109:8099/bugzilla-3.6.2", "alan.zeng@lonnesol.com", "123456");
    private static final Logger logger = Logger.getLogger(MainFrame.class.getName());
    private ArrayList<ServerData> connectDatas = new ArrayList<ServerData>();
    private ServerTree connectTree;
    private static MainFrame frame;
    private TimerCenter timerCenter = new TimerCenter();
    private TabPopupMenu tabPopupMenu;

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        frame = this;

        timerCenter.addTimerEvent("DateTimeFlush", new DateTimeEvent());

        initComponents();
        System.out.println(jtpContext.getUI());
        tabPopupMenu = new TabPopupMenu(jtpContext);
//        jtpContext.setUI(new SynthTabbedPaneUI() {
//            @Override
//            protected MouseAdapter createMouseListener() {
//                final MouseListener delegate = super.createMouseListener();
//                return new MouseAdapter() {
//                    public void mouseClicked(MouseEvent e) {
//                        delegate.mouseClicked(e);
//                    }
//
//                    public void mouseEntered(MouseEvent e) {
//                        delegate.mouseEntered(e);
//                    }
//
//                    public void mouseExited(MouseEvent e) {
//                        delegate.mouseExited(e);
//                    }
//
//                    public void mousePressed(MouseEvent e) {
//                        delegate.mousePressed(e);
//                    }
//
//                    public void mouseReleased(MouseEvent e) {
//                        delegate.mouseReleased(e);
//                        int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY());
//                        if (tabIndex >= 0 && e.getButton() == MouseEvent.BUTTON3) {
//                            tabPopupMenu.show(tabIndex, e.getX(), e.getY());
//                        }
//                    }
//                };
//            }
//        });
        connectTree = new ServerTree();
        jtpConnect.add("Bugzilla连接面板", new JScrollPane(connectTree));

        initDatas();
    }

    public static MainFrame getFrame() {
        return frame;
    }

    private void initDatas() {
        Connection con = BugzillaHelpDB.getConnection();
        ArrayList<ServerData> list = ServerAction.searchAll(con);
        connectDatas.addAll(list);
        SQLTool.closeConnection(con);

        for (ServerData connectData : list) {
            connectTree.addNode(connectData);
        }
    }

    public void addTab(String tabTitle, JComponent jc) {
        jtpContext.addTab(tabTitle, jc);
        jtpContext.setSelectedIndex(jtpContext.getTabCount() - 1);
    }

    public TimerCenter getTimerCenter() {
        return timerCenter;
    }

    public void setStatus(final String text) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                jlStatus.setText(text);
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpopClose = new javax.swing.JPopupMenu();
        jmCloseTab = new javax.swing.JMenuItem();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jpContext = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jpConnects = new javax.swing.JPanel();
        jtpConnect = new javax.swing.JTabbedPane();
        jtpContext = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jpSouth = new javax.swing.JPanel();
        jlStatus = new javax.swing.JLabel();
        jpTime = new javax.swing.JPanel();
        jlCurDate = new javax.swing.JLabel();
        jlCurTime = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jmFile = new javax.swing.JMenu();
        jmConnect = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jmEdit = new javax.swing.JMenu();
        jmTool = new javax.swing.JMenu();
        jmiOptions = new javax.swing.JMenuItem();

        jmCloseTab.setText("Close");
        jmCloseTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmCloseTabActionPerformed(evt);
            }
        });
        jpopClose.add(jmCloseTab);

        jToolBar1.setRollover(true);

        jButton1.setText("Reload");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bugzilla Help Tool");

        jpContext.setLayout(new java.awt.BorderLayout());

        jSplitPane1.setOneTouchExpandable(true);

        jpConnects.setPreferredSize(new java.awt.Dimension(130, 554));
        jpConnects.setLayout(new javax.swing.BoxLayout(jpConnects, javax.swing.BoxLayout.Y_AXIS));
        jpConnects.add(jtpConnect);

        jSplitPane1.setLeftComponent(jpConnects);

        jPanel2.setLayout(new java.awt.BorderLayout());
        jtpContext.addTab("Main Page", jPanel2);

        jSplitPane1.setRightComponent(jtpContext);

        jpContext.add(jSplitPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jpContext, java.awt.BorderLayout.CENTER);

        jpSouth.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(102, 102, 102)), javax.swing.BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(204, 204, 204))));
        jpSouth.setPreferredSize(new java.awt.Dimension(10, 30));
        jpSouth.setLayout(new java.awt.BorderLayout());
        jpSouth.add(jlStatus, java.awt.BorderLayout.CENTER);

        jpTime.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jpTime.setPreferredSize(new java.awt.Dimension(100, 40));
        jpTime.setLayout(new java.awt.GridLayout(2, 1));

        jlCurDate.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlCurDate.setText("Date(yyyy-MM-dd)");
        jpTime.add(jlCurDate);

        jlCurTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlCurTime.setText("Time(HH:mm:ss)");
        jpTime.add(jlCurTime);

        jpSouth.add(jpTime, java.awt.BorderLayout.EAST);

        getContentPane().add(jpSouth, java.awt.BorderLayout.SOUTH);

        jmFile.setMnemonic('F');
        jmFile.setText("File");

        jmConnect.setText("Connect...");
        jmConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmConnectActionPerformed(evt);
            }
        });
        jmFile.add(jmConnect);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jmFile.add(jMenuItem1);

        jMenuBar1.add(jmFile);

        jmEdit.setMnemonic('E');
        jmEdit.setText("Edit");
        jMenuBar1.add(jmEdit);

        jmTool.setText("Tool");

        jmiOptions.setMnemonic('O');
        jmiOptions.setText("Options");
        jmiOptions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiOptionsActionPerformed(evt);
            }
        });
        jmTool.add(jmiOptions);

        jMenuBar1.add(jmTool);

        setJMenuBar(jMenuBar1);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-800)/2, (screenSize.height-600)/2, 800, 600);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jmCloseTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmCloseTabActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jmCloseTabActionPerformed

    private void jmConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmConnectActionPerformed
        ServerInfoPanel serverPanel = new ServerInfoPanel();
        JDialog jDialog = new JDialog(this, "Connect to Bugzilla Server", true);
        jDialog.setContentPane(serverPanel);
        jDialog.pack();
        jDialog.setLocationRelativeTo(this);
        jDialog.setVisible(true);

        if (serverPanel.isOkAction()) {
            ServerData serverData = serverPanel.getConnectData();
            connectDatas.add(serverData);

            serverData.setId(DateTool.getCurrentTime());
            Connection con = BugzillaHelpDB.getConnection();
            ServerAction.insertOne(con, serverData);
            SQLTool.closeConnection(con);

            connectTree.addNode(serverData);
        }
    }//GEN-LAST:event_jmConnectActionPerformed

    private void jmiOptionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiOptionsActionPerformed
        JDialog jDialog = new JDialog(this, "Option Setting");
        jDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        jDialog.setSize(500, 300);
        jDialog.getContentPane().add(new OptionPanel());
        jDialog.setLocationRelativeTo(this);
        jDialog.setVisible(true);
    }//GEN-LAST:event_jmiOptionsActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        LoggerUtil.config();

        logger.log(Level.INFO, "Program Start");


        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel jlCurDate;
    private javax.swing.JLabel jlCurTime;
    private javax.swing.JLabel jlStatus;
    private javax.swing.JMenuItem jmCloseTab;
    private javax.swing.JMenuItem jmConnect;
    private javax.swing.JMenu jmEdit;
    private javax.swing.JMenu jmFile;
    private javax.swing.JMenu jmTool;
    private javax.swing.JMenuItem jmiOptions;
    private javax.swing.JPanel jpConnects;
    private javax.swing.JPanel jpContext;
    private javax.swing.JPanel jpSouth;
    private javax.swing.JPanel jpTime;
    private javax.swing.JPopupMenu jpopClose;
    private javax.swing.JTabbedPane jtpConnect;
    private javax.swing.JTabbedPane jtpContext;
    // End of variables declaration//GEN-END:variables

    private class DateTimeEvent implements TimerEvent {

        @Override
        public boolean throughCondition() {
            return true;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String[] split = DateTool.getCurrentTime().split(" ");
            jlCurDate.setText(split[0]);
            jlCurTime.setText(split[1]);
        }
    }
}
